package com.imooc.oa.controller;

import com.alibaba.fastjson.JSON;
import com.imooc.oa.entity.Employee;
import com.imooc.oa.entity.LeaveForm;
import com.imooc.oa.entity.User;
import com.imooc.oa.service.LeaveFormService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "LeaveFormServlet",urlPatterns = "/leave/*")
public class LeaveFormServlet extends HttpServlet {
    private LeaveFormService leaveFormService=new LeaveFormService();//用来将LeaveForm对象持久化的类
    private Logger logger= LoggerFactory.getLogger(LeaveFormServlet.class);//用来在日志中输出错误信息的类
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String url=request.getRequestURI();
        //获得"/leave"后面的url
        String methodName=url.substring(url.lastIndexOf("/")+1);
        if(methodName.equals("create"))
        {
            this.create(request, response);

        }else if(methodName.equals("list"))
        {
            this.getLeaveFormList(request, response);
        }else if(methodName.equals("audit"))
        {
            this.audit(request, response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         this.doPost(request, response);
    }

    /**
     * 创建请假单
     * @param request
     * @param response
     * @throws IOException
     */
    private void create(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //接收请假单各项数据
        HttpSession httpSession=request.getSession();
        User user=(User)httpSession.getAttribute("login_user");
        String formType=request.getParameter("formType");
        String strStartTime=request.getParameter("startTime");
        String strEndTime=request.getParameter("endTime");
        String reason=request.getParameter("reason");
        //将表单提交的字符串转换成java.util.Date类型
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd-HH");
        //用来存放提交请假申请是否成功的结果
        Map result=new HashMap();
        try {
            LeaveForm leaveForm=new LeaveForm();
            //将数据设置给leaveForm对象
            leaveForm.setFormType(Integer.parseInt(formType));
            leaveForm.setReason(reason);
            leaveForm.setEmployeeId(user.getEmployeeId());
            leaveForm.setCreatTime(new Date());
            leaveForm.setStartTime(format.parse(strStartTime ));
            leaveForm.setEndTime(format.parse(strEndTime));
            //2.调用业务逻辑方法
            //将赋完值LeaveForm对象通过LeaveFormService类的createLeaveForm()方法进行持久化
            LeaveForm leaveForm1=leaveFormService.createLeaveForm(leaveForm);
            result.put("code",0);
            result.put("message", "success");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("请假申请异常",e);
            result.put("code",e.getClass().getSimpleName());
            result.put("message", e.getMessage());
        }
        //3.组织响应数据
        String json= JSON.toJSONString(result);
        response.getWriter().println(json);

    }

    /**
     * 查询需要审核的请假单列表(指定的审核员)
     * @param request
     * @param response
     * @throws IOException
     */
    private void getLeaveFormList(HttpServletRequest request,HttpServletResponse response) throws IOException {
        HttpSession session=request.getSession();
        //通过session获得当前登录用户对象将要审批请假单(即需要当前用户使用审批权力进行审批的请假单)
        User user=(User)session.getAttribute("login_user");
        List<Map> formList = leaveFormService.getLeaveFormList("process", user.getEmployeeId());
        Map result=new HashMap();
        result.put("code",0);//为0代表服务器端处理成功
        result.put("msg","");//服务器返回的具体文本消息
        result.put("count",formList.size());//代表没有分页时原始数据的总数
        result.put("data",formList);//查询结果对象
        String json=JSON.toJSONString(result);
        response.getWriter().println(json);//ajax传递字符串
    }

    /**
     * 处理审批操作
     * @param request
     * @param response
     * @throws IOException
     */
    private void audit(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String formId=request.getParameter("formId");
        String result=request.getParameter("result");
        String reason=request.getParameter("reason");
        User user = (User) request.getSession().getAttribute("login_user");
        Map mpResult=new HashMap();
        try {
            leaveFormService.audit(Long.parseLong(formId), user.getEmployeeId(), result, reason);
            mpResult.put("code",0);
            mpResult.put("message", "success");
        } catch (NumberFormatException e) {
            logger.error("请假单审核失败",e);
            mpResult.put("code",e.getClass().getSimpleName());
            mpResult.put("message", e.getMessage());
            e.printStackTrace();
        }
        String json=JSON.toJSONString(mpResult);
        response.getWriter().println(json);


    }
}
